import datetime
import json
import time

from libs.comps.common.component import manager , TComponentManager , TComponent
from libs.comps.common.compSchedule import TCompSchedule
from libs.comps.common.compDB import TCompDB
from libs.comps.common.compTDB import TCompTDB
from libs.comps.common.compKV import TCompKV
import os.path

class TIotApi(TCompSchedule) :
    def __init__(self , _manager):
        super().__init__(_manager)
        self.handlers ={
            "updateContinueQuery": self.updateContinueQuery
        }
    @property
    def db(self):
        res: TCompDB= None
        try:
            dbCode = self.compSettings['dbCode']
            res = self.manager.getComp("TCompDB" , dbCode)
        except Exception as er :
            self.manager.log(self , er)
        return res
    @property
    def tdb(self):
        res: TCompTDB= None
        try:
            code = self.compSettings['tdbCode']
            res = self.manager.getComp("TCompTDB" , code)
        except Exception as er :
            self.manager.log(self , er)
        return res
    @property
    def kv(self):
        res: TCompKV= None
        try:
            code = self.compSettings['compKvCode']
            res = self.manager.getComp("TCompKV" , code)
        except Exception as er :
            self.manager.log(self , er)
        return res

    def updateContinueQuery(self):
        res={}
        try:
            cqRes = self.db.queryByKey("iot/iotapi/continue_query",{})
            cqs = []
            if cqRes['queryStatus']==1 :
                devs = cqRes['datasetList'][0]
                for item in devs:
                    cqs.append(item['dropCq1d'])
                    cqs.append(item['dropCq1h'])
                    cqs.append( item['continueQuery_1d'])
                    cqs.append( item['continueQuery_1h'])
                for cqSQL in cqs:
                    try:
                        ri= self.tdb.query(cqSQL)
                        print(ri)
                    except Exception as erItem:
                        self.manager.log(self , erItem)
                res = self.tdb.getContinueQueries()
        except Exception as er:
            self.manager.log(self , er)
        return res
manager.registCompType("TIotApi", TIotApi)